package com.chookss.tools;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * Created by Administrator on 2018/7/4.
 */
//RecyclerView Grid 分割线
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
//    int spanCount = 3;//跟布局里面的spanCount属性是一致的
//    int spacing = 5;//每一个矩形的间距
//    boolean includeEdge = true;//如果设置成false那边缘地带就没有间距
    private int spanCount;
    private int widthSpacing,heigthSpacing;
    private boolean includeEdge;
//横竖间隔一样
    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.widthSpacing = spacing;
        this.heigthSpacing = spacing;
        this.includeEdge = includeEdge;
    }
    //可以动态配置横竖间隔
    public GridSpacingItemDecoration(int spanCount, int spacing, int heigthSpacing,  boolean includeEdge) {
        this.spanCount = spanCount;
        this.widthSpacing = spacing;
        this.heigthSpacing = heigthSpacing;
        this.includeEdge = includeEdge;
    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = widthSpacing - column * widthSpacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * widthSpacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = heigthSpacing;
            }
            outRect.bottom = heigthSpacing; // item bottom
        } else {
            outRect.left = column * widthSpacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = widthSpacing - (column + 1) * widthSpacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = heigthSpacing; // item top
            }
        }
    }
}
